package cn.ajb.filemanager.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import cn.ajb.filemanager.entity.FileManager;
import cn.ajb.filemanager.entity.SysParamDict;
import cn.ajb.filemanager.entity.User;
import cn.ajb.filemanager.service.FileManagerService;
import cn.ajb.filemanager.service.SysParamDictService;
import cn.ajb.filemanager.service.UserService;
import cn.ajb.filemanager.util.Contant;
import cn.ajb.filemanager.util.JSONResult;
import cn.ajb.filemanager.util.PageModel;
import cn.ajb.filemanager.vo.TreeViewVo;

/**
 * 文件管理controller
 * @author weilu
 *
 */
@Controller
@RequestMapping("/fileManagerController")
public class FileManagerController {
	
	@Autowired
	private FileManagerService fileManagerService;
	@Autowired
	private SysParamDictService sysParamDictService;
	@Autowired
	private UserService userService;
	@Autowired
	private Contant contant;
	
	private static final Logger logger = Logger.getLogger(FileManagerController.class);
	/**
	 * 通过父级id,查找其底下所有的子集
	 * @param parentId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getFileManagerListByParentId")
	public String getFileManagerListByParentId(Integer parentId ,String fileName ,Integer materiel ,Integer sysType ,Integer productType,Integer pageNo,Integer pageSize,HttpServletRequest request,ModelMap modelMap) throws Exception{
		if(pageNo==null){
			pageNo = 1;
		}
		if(pageSize==null){
			pageSize = contant.getPageSize();
		}
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("parentId", parentId);
		paramMap.put("fileName", fileName);
		paramMap.put("materiel", materiel);
		paramMap.put("sysType", sysType);
		paramMap.put("productType", productType);
		
		PageModel<FileManager> pageModel = fileManagerService.selectFileManagerListByParentIdAndPage(paramMap,pageNo ,pageSize,request);
		List<FileManager> list = fileManagerService.selectFileManagerListById(new ArrayList<FileManager>(),parentId);
		modelMap.put("pageModel", pageModel);
		System.out.println(list);
		modelMap.put("breadcrumbList", list);
		return "main";
	}
	/**
	 * 获取fileManager的树形结构
	 * @return
	 */
	@RequestMapping("/getFileManagerTree")
	public @ResponseBody TreeViewVo getFileManagerTree(){
		 return fileManagerService.selectFileManagerTree();
	}
	/**
	 * 添加文件夹
	 * @param parentId
	 * @param parentStrCn
	 * @param level
	 * @param fileName
	 * @param request
	 * @return
	 */
	@RequestMapping("/insertFileFolder")
	public @ResponseBody JSONResult<String> insertFileFolder(
			@RequestParam(required = true) Integer parentId,
			@RequestParam(required = true) String parentStrCn,
			@RequestParam(required = true) Integer level,
			@RequestParam(required = true) String fileName,String remarks,HttpServletRequest request){
		return fileManagerService.insertFileFolder(parentId,parentStrCn,level,fileName,remarks,request);
	}
	
	/**
	 * 文件上传
	 * @param fileUpload
	 * @param parentId
	 * @param parentStrCn
	 * @param level
	 * @throws IOException
	 */
	  @RequestMapping("/fileUpload")
	  public  @ResponseBody JSONResult<String>  fileUpload(
	    		@RequestParam("fileUpload") CommonsMultipartFile fileUpload,
	    		@RequestParam(required = true) Integer parentId,
	    		@RequestParam(required = true) String parentStrCn,
	    		@RequestParam(required = true) Integer level,
	    		@RequestParam String sysType,@RequestParam String productName,
	    		@RequestParam String productType,@RequestParam String specialNum,
	    		@RequestParam String productModel,@RequestParam String uploadUser,
	    		@RequestParam String usageScenarios,@RequestParam String documentType,
	    		@RequestParam String version,@RequestParam String materiel,
	    		HttpServletRequest request
	    		) throws IOException {
		  System.out.println("---------------fileUpload()------------");
		//在上传文件是同时生成二维码 需要传入request id 
		 return fileManagerService.fileUpload(fileUpload, parentId, parentStrCn, level, request,
				 sysType ,productName ,productType ,productModel ,usageScenarios ,documentType ,version ,materiel ,uploadUser ,specialNum);
	    }
	  @ExceptionHandler(Exception.class)         
	    public @ResponseBody JSONResult<String> handleException(Exception ex,HttpServletRequest request) {       
	         if (ex instanceof MaxUploadSizeExceededException){  
	        	 long maxSize = ((MaxUploadSizeExceededException) ex).getMaxUploadSize();
		         JSONResult<String> jsonResult = new JSONResult<String>();
		          jsonResult.setStatus(JSONResult.STATUS_SUCCESS);
		          jsonResult.setMsg("上传文件不能超过50MB,上传文件失败");
		          return jsonResult ;
	         }
	         return null;
	    }    
	  /**
	   * 删除文件夹或文件
	   * @param id
	   * @param request
	   * @return
	   */
	  @RequestMapping("/delete")
	  public @ResponseBody JSONResult<String>  delete(@RequestParam(required = true) Integer id,HttpServletRequest request){
			return fileManagerService.delete(id,request);
	}
	 /**
	  * 修改文件夹
	  * @param id
	  * @param fileName
	  * @param remarks
	  * @param parentId
	  * @param request
	  * @return
	  */
	 @RequestMapping("/updateFolder")
	 public @ResponseBody JSONResult<String> updateFolder(
				@RequestParam(required = true) Integer id,
				@RequestParam(required = true) String fileName,
				@RequestParam String remarks,
				@RequestParam(required = true) Integer parentId,
				HttpServletRequest request){
			return fileManagerService.updateFolder(id, fileName, remarks, parentId, request);
	}
	 /**
	  * 获取文件详情
	  * @param id
	  * @return
	  */
	  @RequestMapping("/selectFileManagerDetailById")
	  public String selectFileManagerDetailById(
				@RequestParam(required = true) Integer id ,@RequestParam(required = true) Integer fileType ,ModelMap modelMap){
		 FileManager fileManager = fileManagerService.selectFileManagerDetailById(id);
		 modelMap.put("fileManager", fileManager);
		 if(fileType==1) {
			 List<User> userList = userService.selectUserList();
			 List<SysParamDict> spdList = sysParamDictService.selectSysParamDictlist();
			 modelMap.put("userList", userList);
			 modelMap.put("spdList", spdList);
			 System.out.println(fileManager);
			 System.out.println(spdList);
			 return "updateFile";
		 }
		 return "updateFolder";
	}
	 /**
	  * 修改文件
	  * @param id
	  * @param fileName
	  * @param oldFileName
	  * @param parentStrCn
	  * @param parentId
	  * @param remarks
	  * @return
	  */
	 @RequestMapping("/updateFileManagerFile")
	 public @ResponseBody JSONResult<String> updateFileManagerFile(
		@RequestParam(required = true) Integer id,@RequestParam(required = true) String fileName, 
		@RequestParam(required = true) String oldFileName,@RequestParam(required = true) String parentStrCn,
		@RequestParam(required = true) Integer parentId,
		@RequestParam String remarks,@RequestParam String sysType,@RequestParam String productName,
		@RequestParam String productType,@RequestParam String specialNum,@RequestParam String productModel,
		@RequestParam String uploadUser,@RequestParam String usageScenarios,@RequestParam String documentType,
		@RequestParam String version,@RequestParam String materiel,HttpServletRequest request){
		  System.out.println(sysType+"----------------------");
		FileManager fileManager = new FileManager(id,fileName,remarks,parentStrCn,new Date(),sysType,productName,productType,specialNum,productModel,uploadUser ,usageScenarios,documentType,version,materiel);
		return fileManagerService.updateFileManagerFile(fileManager,oldFileName,parentId,request);
	} 
	/**
	 * 文件下载
	 * @param id
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/dowlond")
	public void dowlond(@RequestParam(required = true) Integer id,HttpServletRequest request,HttpServletResponse response){
		 logger.info("/fileManagerController/dowlond_______"+id);	
		try {
				
				List<FileManager> dowloandFilemanager = fileManagerService.selectFileManagerListById(new ArrayList<FileManager>(), id);
				FileManager filemanager=dowloandFilemanager.get(0);
				response.setContentType("application/x-download");
				if(filemanager.getFileType()==0){
					response.setHeader("Content-Disposition", "attachment;filename=" + new String((dowloandFilemanager.get(0).getFileName()+".zip").getBytes(), "ISO-8859-1"));
				}else{
					response.setHeader("Content-Disposition", "attachment;filename=" + new String(dowloandFilemanager.get(0).getFileName().getBytes(), "ISO-8859-1"));
				}
				ServletOutputStream outputStream = response.getOutputStream();
				
				if(filemanager.getFileType()==0){
					fileManagerService.dowlondZip(request,filemanager,outputStream);
				}else{
					
					fileManagerService.dowlondFile(request,filemanager,outputStream);
				}
				if(outputStream != null){
					outputStream.close();
				}
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	
	//根据系统字典类型查找到文件
		@RequestMapping(value="/searchFilManagerFile") 
		public String searchFilManagerFile(
				 String fileName ,String sysType ,String productName ,String productType,
				 String specialNum,String productModel,String uploadUser,String usageScenarios,
				 String documentType ,String version ,String materiel,
				Integer pageNo,Integer pageSize,HttpServletRequest request,ModelMap modelMap){
			if(pageNo==null){
				pageNo = 1;
			}
			if(pageSize==null){
				pageSize = contant.getPageSize();
			}
			PageModel<FileManager> pageModel = fileManagerService.searchFilManagerFile(fileName, sysType, productName, productType, specialNum, productModel, uploadUser, usageScenarios, documentType, version, materiel, pageNo, pageSize, request, modelMap);
			modelMap.put("pageModel", pageModel);
			return "main";
		}
}
